package com.qf.hospital.controller;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageInfo;
import com.qf.hospital.dto.ReportDTO;
import com.qf.hospital.entity.Cashier;
import com.qf.hospital.entity.Pharmacy;
import com.qf.hospital.entity.Report;
import com.qf.hospital.entity.SysUser;
import com.qf.hospital.enums.HospitalExceptionEnums;
import com.qf.hospital.service.*;
import com.qf.hospital.vo.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zjw
 * @description 门诊管理-用户挂号对应的Controller
 * @date 2021/10/20 9:30
 */
@RestController
public class CaoController {

    private Logger log = LoggerFactory.getLogger(CaoController.class);

    @Autowired
    private ReportService reportService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private RegisteredTypeService registeredTypeService;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private PharmacyService pharmacyService;


    // ================================用户挂号==================================================


    /**
     * 查询患者信息
     *
     * @param cc   1-查看全部，2-查看当前挂号信息，3-查看预约挂号信息
     * @param name 检索挂号用户信息的条件，并没有指定检索哪个字段
     * @return
     */
    @GetMapping("/cao/index")
    public List<ReportVO> index(@RequestParam(defaultValue = "1") Integer cc, String name) {
        //1. 调用Service查询数据
        List<ReportVO> data = reportService.findPatientInfo(cc, name);

        //2. 响应
        return data;
    }


    /**
     * 查询科室类型
     *
     * @return
     */
    @PostMapping("/cao/seldep")
    public List<DepartmentVO> selectDepartment() {
        return departmentService.selectDepartment();
    }

    /**
     * 查询科室类型
     *
     * @return
     */
    @PostMapping("/cao/selreg")
    public List<RegisteredTypeVO> selectRegisteredType() {
        return registeredTypeService.selectRegisteredType();
    }


    /**
     * 查询医生信息
     * @param registeredId    挂号类型
     * @param departmentId    科室类型
     * @return
     */
    @PostMapping("/cao/seldoctor")
    public List<DoctorVO> selectDoctor(Integer registeredId, Integer departmentId) {
        //1. 校验参数
        if (registeredId == null || departmentId == null) {
            log.info("【查询医生信息】 请求参数不合法！ registeredId = {},departmentId = {}", registeredId, departmentId);
            return null;
        }

        //2. 查询
        List<DoctorVO> result = doctorService.findDoctorByRegisteredIdAndDepartmentId(registeredId, departmentId);

        //3. 返回
        return result;
    }


    /**
     * 查询挂号费用
     * @param registeredId
     * @return
     */
    @PostMapping("/cao/selRegMoney")
    public Integer selectRegisteredMoney(Integer registeredId){
        //1. 校验参数
        if(registeredId == null){
            log.info("【查询医生信息】 请求参数不合法！ registeredId = {}", registeredId);
            return -1;
        }

        //2. 查询数据 & 返回
        return registeredTypeService.findPriceByRegisteredId(registeredId);
    }


    /**
     * 手机号&身份证号校验
     * @param phone   手机号
     * @param carid    身份证号
     * @return
     */
    @PostMapping("/cao/phone")
    public Integer checkPhoneAndCarid(String phone,String carid){
        //1. 参数校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(carid)){
            log.info("【校验手机号&身份证号】 手机或者身份证信息为空！");
            return 0;
        }

        //2. 调用Service校验数据并返回
        return reportService.checkPhoneAndCarid(phone,carid);
    }


    /**
     * 完成添加患者信息
     * @param reportDTO   接收的参数
     * @param bindingResult
     * @return
     */
    @PostMapping("/cao/addReport")
    public R addReport(@Valid ReportDTO reportDTO, BindingResult bindingResult){
        //1. 校验参数
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            log.info("【添加患者信息】 请求参数异常，msg = {}",msg);
            return R.error(HospitalExceptionEnums.REQUEST_PARAMETER_ERROR.getCode(),msg);
        }
        //2. 封装录入人信息
        Subject subject = SecurityUtils.getSubject();
        SysUser sysUser = (SysUser) subject.getPrincipal();
        if(sysUser == null){
            log.info("【添加患者信息】 用户登录已超时！");
            return R.error(HospitalExceptionEnums.LOGIN_TIMEOUT);
        }
        reportDTO.setUsers(sysUser.getRealName());

        //3. 调用Service保存
        reportService.addReport(reportDTO);

        //4. 返回
        return R.ok("添加患者信息成功！");
    }


    // ================================处方划价==================================================


    /**
     * 处方划价-展示患者信息
     * @param name
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/caotake/tselpreson")
    public R selectPerson(String name,
                          @RequestParam(defaultValue = "1")Integer page,
                          @RequestParam(defaultValue = "10")Integer limit){
        //1. 调用Service查询数据
        PageInfo<Report> pageInfo = reportService.findPerson(name,page,limit);

        //2. 封住数据
        long count = pageInfo.getTotal();
        List<ReportVO> data = new ArrayList<>();
        for (Report report : pageInfo.getList()) {
            ReportVO vo = new ReportVO();
            BeanUtils.copyProperties(report,vo);
            data.add(vo);
        }

        //3. 返回数据
        return R.ok(count,data);
    }


    /**
     * 展示药品信息
     * @param drugname
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/caocc/seldrug")
    public R selectDrug(String drugname,
                        @RequestParam(defaultValue = "1")Integer page,
                        @RequestParam(defaultValue = "10")Integer limit){
        //1. 查询药品信息
        PageInfo<Pharmacy> pageInfo = pharmacyService.selectDrug(drugname,page,limit);

        //2. 封装
        long count = pageInfo.getTotal();
        List<DrugVO> data = new ArrayList<>();
        pageInfo.getList().forEach(pharmacy -> {
            data.add(new DrugVO(pharmacy.getPharmacyName(),pharmacy.getDrugStoreNum(),pharmacy.getUnitName(),pharmacy.getSellingPrice()));
        });
        //3. 返回
        return R.ok(count,data);
    }

}
